#include "stm32f1xx_hal.h"
#include "crcLib.h"
#include "config.h"


uint8_t ModbusFlag = 0,UartFlag = 0;
int MuodbusCont = 0;
uint8_t ModbudData[64],ModbudDataBuff;
uint8_t REG[32];


extern double PH,DO,NH4,temp;
uint16_t ph,do1,nh4,tem;

//modbus数据处理
void data_pro()
{
	if(ModbudData[0] == 0x01&&ModbudData[1] == 0x03)
	{

		HAL_UART_Transmit(&huart1, ModbudData, MuodbusCont, 1000);

		tem = (int)(temp*100);
		ph = (int)(PH*100);
		do1 = (int)(DO*100);
		nh4 = (int)(NH4*100);

		REG[0] = tem>>8;
		REG[1] = tem;
		REG[2] = ph>>8;
		REG[3] = ph;
		REG[4] = do1>>8;
		REG[5] = do1;
		REG[6] = nh4>>8;
		REG[7] = nh4;


		//定义寄存器起始地址
		uint16_t RegStart = ModbudData[2];
		RegStart = (((RegStart<<8))|ModbudData[3])*2;

		//定义寄存器个数
		uint16_t RegNum;
		RegNum =  (uint16_t)(ModbudData[4]<<8)|ModbudData[5];

		//返回字节个数
		ModbudData[2] = 2*RegNum;

		MuodbusCont = 3;
		//对应寄存器的数据
		for(uint16_t x = 0;x<ModbudData[2];x++)
		{
			ModbudData[MuodbusCont++] = REG[RegStart++];
		}

		//crc检验
		uint16_t crc = crc16_modbus(ModbudData,MuodbusCont);
		ModbudData[MuodbusCont++] = crc;
		ModbudData[MuodbusCont++] = crc>>8;

		//返回数据
		HAL_UART_Transmit(&huart3, ModbudData, MuodbusCont, 1000);
		HAL_UART_Transmit(&huart1, ModbudData, MuodbusCont, 1000);
	}
	ModbusFlag = 0;
	MuodbusCont = 0;
}


//modbus资源初始化
int modbus_init()
{
	HAL_UART_Receive_IT(&huart3, &ModbudDataBuff, 1);


	HAL_UART_Transmit(&huart3, "modbus_init",11, 1000);
}




//定时器回调空闲中断
void Uart3_Tim_Call()
{
	//3.5ms
	//串口空闲中断
	ModbusFlag = 1;
	HAL_TIM_Base_Stop(&htim1);
	__HAL_TIM_SET_COUNTER(&htim1,0);
	data_pro();

}



//串口回调
void Uart3_call()
{
		UartFlag = 2;
		HAL_TIM_Base_Stop(&htim1);
		__HAL_TIM_SET_COUNTER(&htim1,0);
		HAL_TIM_Base_Start_IT(&htim1);
		ModbudData[MuodbusCont++] = ModbudDataBuff;
		HAL_UART_Receive_IT(&huart3,&ModbudDataBuff, 1);
}

